import os
import pytest
from selenium import webdriver
from selenium.webdriver import ChromeOptions
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from pages.trunk import Trunk
from configs.settings import BASE_DIR, SCREENSHOT, REPORT_DIR, ENV_API_TXT_FILE, ENV_WEB_TXT_FILE
from libraries.logger import log


def unlink_handler(file):
    try:
        os.unlink(file)
    except FileNotFoundError:
        pass


@pytest.fixture(scope='session', autouse=True)
def env_clear():
    os.chdir(SCREENSHOT)
    for i in os.listdir(SCREENSHOT):
        unlink_handler(i)
    log.info(f"目录{SCREENSHOT}已清空")
    os.chdir(REPORT_DIR)
    for i in os.listdir(REPORT_DIR):
        if i.endswith('.json') or i.endswith('.png') or i.endswith('.txt'):
            unlink_handler(i)
    log.info(f"目录{REPORT_DIR}已清空")
    os.chdir(BASE_DIR)
    yield


def pytest_addoption(parser):
    """注册自定义参数 --api-url 到配置对象"""
    parser.addoption("--api-url", action="store",
                     default="https://apix.azazie.com/",
                     type=str,
                     help="将命令行参数 '--api-url' 添加到 pytest 配置中")


@pytest.fixture(scope="session")
def api_env(request):
    """从配置对象中读取自定义参数的值"""
    return request.config.getoption("--api-url")


@pytest.fixture(autouse=True)
def set_api_env(api_env):
    """将自定义参数的值写入环境配置文件"""
    with open(ENV_API_TXT_FILE, 'w', encoding='utf-8') as f:
        f.write(api_env)
    log.info(f'--api-url：{api_env}')


def browser_options(is_local=False):
    """浏览器配置"""
    options = ChromeOptions()
    options.add_experimental_option('mobileEmulation', {'deviceName': 'iPhone X'})  # 手机模式
    if is_local is False:
        options.add_argument('--headless')  # 无头模式
        options.add_argument('--no-sandbox')  # 让Chrome执行在root权限下（linux）
        options.add_argument('--disable-dev-shm-usage')
    # options.add_argument('window-size=375×812')  # 指定浏览器分辨率
    # options.add_argument("–-disable-web-security")  # 关闭安全策略
    options.add_argument('--disable-gpu')  # 禁用GPU加速
    options.add_argument('--disable-javascript')
    # options.add_argument('--incognito')  # 无痕模式
    options.add_argument('--allow-running-insecure-content')  # https页面允许从http链接引用javascript/css/plug-ins
    # options.add_argument('--blink-settings=imagesEnabled=false')  # 不加载图片
    options.add_experimental_option('excludeSwitches', ['enable-automation'])  # 屏蔽'CHROME正受到组件控制'的提示
    options.add_experimental_option(
        "prefs", {'credentials_enable_service': False,
                  'profile.password_manager_enabled': False,  # 屏蔽'保存密码'提示框
                  'profile.default_content_setting_values': {'notifications': 2}}  # 屏蔽‘显示通知’
    )
    # options.add_argument('--proxy-server=socks5://192.168.2.66:9005')  # 代理设置
    return options


@pytest.fixture
def driver_setup(base_url):
    """浏览器初始化/隐性等待时间设置"""
    try:
        desired_caps = DesiredCapabilities.CHROME
        desired_caps["javascriptEnabled"] = 'True'
        command_executor = 'http://lebbay:forautotest@18.211.96.2:4444/wd/hub'
        driver = webdriver.Remote(command_executor, desired_capabilities=desired_caps, options=browser_options()) \
            if os.path.exists('/user/src/test/az-web/') \
            else webdriver.Chrome(chrome_options=browser_options(is_local=True))
        # command_executor = 'http://18.209.177.82:30475/wd/hub'
        # driver = webdriver.Remote(command_executor, desired_capabilities=desired_caps, options=browser_options())
        driver.get(base_url)
        log.info(f"打开Chrome浏览器访问URL：{base_url}，当前版本号abtest：{driver.get_cookie('abtest').get('value')}")
        log.info('设置浏览器窗口大小375×812')
        # 设置全局隐性等待时间，单位：s
        driver.implicitly_wait(30)
        log.info('设置隐性等待时间30s')
        tk = Trunk(driver)
        tk.close_coupon_wheel(is_activity=False)
    except Exception as exc:
        log.error(f"WebDriver Exception：{exc}")
        driver.quit()
    else:
        with open(ENV_WEB_TXT_FILE, 'w', encoding='utf-8') as f:
            f.write(base_url)
        yield driver
        log.info('关闭浏览器')
        driver.quit()
